package Events;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Random;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;

import structures.Pace;
import structures.Spaceship;

/**
 * Asteroid Field: 
 * 
 * @author Branon Lyle
 */
@SuppressWarnings("serial")
public class AsteroidField extends PathEvent implements ActionListener{

    private double density;
    private int distance;
    private int price;
    private double probability;
    private Random generator;
    private NumberFormat formatter;
    private JButton btnThrough, btnAround, btnGuide;
    private JTextArea txt;
    private static Image image;
    private Spaceship ship;
    private JTextArea log;
    
    /**
     * Constructor
     * @param name
     * @param description
     * @param location
     */
    public AsteroidField(String name, String description, int location) {
        super(name, description, location);
        
        // Randomly generate density and length
        generator = new Random(System.currentTimeMillis());
        density = generator.nextDouble(); //nextGaussian();
        distance = generator.nextInt(16) + 5; //random distance between 5 and 20 
        probability = 1 - (density * distance)/20;
        price = (int) ((1/probability) * 50);
        formatter = new DecimalFormat("#.####");
        
        this.setPreferredSize(new Dimension(700, 700));
        
        try
        {
          image = javax.imageio.ImageIO.read(new java.net.URL(getClass().getResource("Asteroid_Field.jpg"), "Asteroid_Field.jpg"));
        }
        catch (Exception e) { /*handled in paintComponent()*/ }
        
        this.setLayout(null);
        
        btnThrough = new JButton("Travel Through");
        btnThrough.setBounds(100, 259, 150, 23);
        btnThrough.addActionListener(this);
        add(btnThrough);
        
        btnAround = new JButton("Travel Around");
        btnAround.setBounds(255, 259, 125, 23);
        btnAround.addActionListener(this);
        add(btnAround);
        
        btnGuide = new JButton("Purchase A Guide");
        btnGuide.setBounds(385, 259, 150, 23);
        btnGuide.addActionListener(this);
        add(btnGuide);
        
        txt = new JTextArea("You Encountered an Asteroid Field at " + location + "!\n\n", 10, 20);
        
        txt.append("Asteroid Field Information: \n\n");
        txt.append("Asteroid Density: \t" + formatter.format(density) + "\n");
        txt.append("Length of Asteroid Field: \t" + distance + "\n");
        txt.append("Probability of Success: \t" + formatter.format(probability) + "\n");
        txt.append("Price of Guide:   \t" + price + "\n");
        
        txt.setEditable(false);
        txt.setLineWrap(true);
        txt.setWrapStyleWord(true);
        txt.setBorder(BorderFactory.createLineBorder(Color.blue, 2));
        txt.setBounds(125, 286, 378, 200);
        add(txt);
  
    }

    
  
    /**
     * Paints Image
     * @param g the Graphics Object on which to draw
     */
    @Override
    protected void paintComponent(Graphics g)
    {
      super.paintComponent(g); 
      if (image != null)
        g.drawImage(image, 125,10,378,243,this);
    }
    
    @Override
    public boolean isRunning() {
        // TODO Auto-generated method stub
        return running;
    }

    @Override
    public void nextPhase() {
        // TODO Auto-generated method stub

    }

    @Override
    public void prevPhase() {
        // TODO Auto-generated method stub

    }
    
    /**
     * Execute this Event
     * @param s the game Spaceship
     */
    @Override
    public void execute(Spaceship s) {
        this.ship = s;
        ship.setLocation(location);
        ship.setLastLocation(location);
        running = true;
    }
    
    /**
     * Executes this Event
     * @param s the game Spaceship
     * @param log the game progress log
     */
    public void execute(Spaceship s, JTextArea log) {
        execute(s);
        this.log = log;
        log.append(txt.getText());
    }
    
    /**
     * Button Listening Stuff
     * @param e the ActionEvent caused by the clicking of one of the buttons
     */
    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        Object[] options = {"Ok"};
        if (e.getSource() == btnThrough) {
            double tmp = generator.nextDouble();
            System.out.println(tmp);
            if (tmp < probability) {
                while (ship.getLocation() < (location+distance)){
                    ship.move();
                    if (ship.getLocation() != 0) {
                        log.append("\n" + ship.getUpdateText() + "\n");
                        ship.useRations();
                        log.append(ship.getUpdateText() + "\n");
                        ship.useWater();
                        log.append(ship.getUpdateText() + "\n");
                        log.setCaretPosition(log.getDocument().getLength()); // moves view to just added lines
                    }
                }
                JOptionPane.showOptionDialog(this, "Congratulations! You made it through alive.", "Yay!", JOptionPane.DEFAULT_OPTION,
                        JOptionPane.WARNING_MESSAGE, null, options, options[0]);
                ship.setLastLocation(ship.getLocation());
                ship.updateUpdateText();
                log.append("\nYou made it through the Asteroid Field alive!\n");
            }
            else {
                JOptionPane.showOptionDialog(this, "You were hit by an asteroid! You die!", "Oh NOOOO!", JOptionPane.DEFAULT_OPTION,
                        JOptionPane.WARNING_MESSAGE, null, options, options[0]);
                System.exit(0);
            }
            running = false;            
        }
        else if (e.getSource() == btnAround) {
            Pace pace = ship.getPace();
            double local = location;
            while (local < (location+2*distance)){
                //ship.move();
                if (ship.getLocation() != 0) {
                    //log.append("\n" + ship.getUpdateText() + "\n");
                    ship.useRations();
                    log.append("\n" + ship.getUpdateText() + "\n");
                    ship.useWater();
                    log.append(ship.getUpdateText() + "\n");
                    log.setCaretPosition(log.getDocument().getLength()); // moves view to just added lines
                } 
                local += pace.getPace();
            }
            JOptionPane.showOptionDialog(this, "You traveled " + 2*distance + " around the Asteroid Field.", "Success", JOptionPane.DEFAULT_OPTION,
                    JOptionPane.WARNING_MESSAGE, null, options, options[0]);
            log.append("\nYou traveled " + 2*distance + " around the Asteroid Field.\n");
            running = false; 
        }
        else if (e.getSource() == btnGuide) {
            while (ship.getLocation() < (location+distance)){
                ship.move();
                if (ship.getLocation() != 0) {
                    log.append("\n" + ship.getUpdateText() + "\n");
                    ship.useRations();
                    log.append(ship.getUpdateText() + "\n");
                    ship.useWater();
                    log.append(ship.getUpdateText() + "\n");
                    log.setCaretPosition(log.getDocument().getLength()); // moves view to just added lines
                }
            }
            ship.getInventory().modifyWallet(-price);
            JOptionPane.showOptionDialog(this, "You were guided through the asteriod field!", "Yay!", JOptionPane.DEFAULT_OPTION,
                    JOptionPane.WARNING_MESSAGE, null, options, options[0]);
            ship.setLastLocation(ship.getLocation());
            log.append("\nYou spent " + price + " on a guide and made it through the asteroid field!\n");
            running = false;
        }
    }
    
    /**
     * Distance accessor
     * @return distance
     */
    public int getDistance() {
        return distance;
    }
    
}
